package service;

import org.springframework.stereotype.Service;
import pojo.UserForm;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    private static final String USER_FILE = "user.dat";
    private List<UserForm> userList = new ArrayList<UserForm>();

    public UserServiceImpl() {
        loadUsersFromFile();
    }

    @Override
    public boolean login(UserForm user) {
        for(UserForm u:userList){
            if(u.getUname().equals(user.getUname()) && u.getUpass().equals(user.getUpass())){
                return true;
            }
        }
        return false;
//        return userList.stream()
//                .anyMatch(u -> u.getUname().equals(user.getUname())
//                        && u.getUpass().equals(user.getUpass()));
    }

    @Override
    public boolean register(UserForm user) {
        // 检查用户是否已存在
        if (userExists(user.getUname())) {
            return false;
        }

        // 检查密码和确认密码是否一致
        if (!user.getUpass().equals(user.getReupass())) {
            return false;
        }

        // 添加到内存列表
        userList.add(user);

        // 保存到文件
        return saveUsersToFile();
    }

    // 检查用户是否已存在
    private boolean userExists(String username) {
        for(UserForm u:userList){
            if(u.getUname().equals(username)){
                return true;
            }
        }
        return false;
//        return userList.stream()
//                .anyMatch(u -> u.getUname().equals(username));
    }

    // 从文件加载用户信息
    private void loadUsersFromFile() {
        File file = new File(USER_FILE);
        if (!file.exists()) {
            return;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    UserForm user = new UserForm();
                    user.setUname(parts[0]);
                    user.setUpass(parts[1]);
                    userList.add(user);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 保存用户信息到文件
    private boolean saveUsersToFile(){
        try (PrintWriter writer = new PrintWriter(new FileWriter(USER_FILE))) {
            for (UserForm user : userList) {
                writer.println(user.getUname() + "," + user.getUpass());
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
